package org.ghost.spring.cloud.zuul.demo.component.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.*;

@Component
public class QueryParamPreFilter extends ZuulFilter {
    private static final Logger logger = LoggerFactory.getLogger(QueryParamPreFilter.class);

    /**
     * PRE_TYPE,路由代理之前执行
     * ROUTE_TYPE,路由代理的时候执行
     * ERROR_TYPE,路由代理出现错误的时候执行
     * POST_TYPE,在ROUTE_TYPE或者ERROR_TYPE执行完成之后执行
     *
     * @return
     */
    @Override
    public String filterType() {
        return PRE_TYPE;
    }

    /**
     * 序号越小越先执行
     *
     * @return
     */
    @Override
    public int filterOrder() {
        return PRE_DECORATION_FILTER_ORDER - 1;
    }

    @Override
    public boolean shouldFilter() {
        logger.info("*****开始执行QueryParamPreFilter.shouldFilter");
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        return StringUtils.isNoneBlank(request.getHeader("token"));
    }

    @Override
    public Object run() throws ZuulException {
        logger.info("*****开始执行QueryParamPreFilter.run");
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        if (request.getParameter("token") != null) {
            ctx.put(SERVICE_ID_KEY, request.getParameter("foo"));
        }
        return null;
    }
}
